<template>
  <div class="tem-table">
    <CHeader :keyword="keyword" @onKeywordChange="onKeywordChange" @onClearKeyword="onClearKeyword" @onSearch="onSearch"
             @onReset="onReset" :hide-new="true">
      <el-form style="display: inline-block">
        <el-form-item style="margin: 0" label="现场：" label-width="100px">
          <el-select filterable v-model="nodeId" placeholder="选择现场" @change="()=>getList()" clearable>
            <el-option label="全部" :value="''"/>
            <el-option v-for="item in nodeOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
    </CHeader>
    <div class="tem-table-box">
      <el-table :data="tableData" :border="true" style="width: 100%" height="100%" v-loading="loading">
        <el-table-column type="expand">
          <template #default="{ row }">
            <div m="10">
              <h3>现场：{{ row.nodeName }}</h3>
              <el-table :data="row.customerList" :border="true">
                <el-table-column label="医院名称" prop="hospitalName"/>
                <el-table-column label="HosID" prop="hospitalId"/>
                <el-table-column label="OrgID" prop="hisOrgId"/>
                <el-table-column label="操作">
                  <template #default="props">
                    <el-button link type="primary" size="small"
                               @click="onBindingUser(props.row.hospitalId, props.row.hisOrgId,props.row.hospitalName, 1)">
                      绑定用户
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName"/>
        <el-table-column label="HosID" prop="hospitalId"/>
        <el-table-column label="OrgID" prop="orgId"/>
        <el-table-column label="操作">
          <template #default="props">
            <el-button link type="primary" size="small"
                       @click="onBindingUser(props.row.hospitalId, props.row.orgId,props.row.customerName, 0)">
              绑定用户
            </el-button>
            <el-button link type="primary" size="small" @click="pullHos(props.row.customerId)">拉取医院</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>


  <el-dialog width="500px" v-model="showEditModel" title="绑定用户">
    <el-form :rules="formRules" ref="formRef" :model="formRef" label-width="120px">
      <el-form-item label="客户" prop="customerName">
        <el-input v-model="editForm.customerName" disabled style="width: 260px;"/>
      </el-form-item>
      <el-form-item label="用户" prop="uids">
        <el-select
            placeholder="请选择用户"
            multiple
            filterable
            v-model="editForm.uids"
            style="width: 260px;"
        >
          <el-option v-for="item in userOptions" :key="item.uid" :label="item.name" :value="item.uid"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onCloseEdit()">取 消</el-button>
      <el-button type="primary" @click="bindingUser(formRef)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {onBeforeMount} from "vue";
import {layoutStore} from '@/store/menu';
import CHeader from '@/components/CHeader.vue';
import {
  editUserBindingCustomer,
  getNodeCustomerList,
  getUserBindingCustomerList,
  pullHospitalList
} from "@/service/HosManager";
import {CustomerMo} from "@/service/entity/CustomerMo";
import {ElMessage, FormInstance} from "element-plus";
import {getAllUserList} from "@/service/UserManager";
import {Customer} from "@/service/entity/Customer";

const store = layoutStore()

const keyword = ref('')
const tableData = ref<Customer[]>([])
const loading = ref(false)
const nodeId = ref('')
const nodeOptions = ref([])

const showEditModel = ref(false)
const userOptions = ref([])
const editForm = reactive({
  type: '',
  hosId: '',
  orgId: '',
  customerName: '',
  uids: []
})
const formRef = ref<FormInstance>()
const formRules = reactive({
  customerId: {required: true, message: '客户ID不可为空', trigger: 'blur'},
})


onBeforeMount(async () => {
  getList()
  const res = await getAllUserList({all: true})
  const arr = []
  for (let user of res.arr) {
    arr.push({
      uid: user.id,
      name: user.name
    })
  }
  userOptions.value = arr
})

const onKeywordChange = (val: string) => {
  keyword.value = val
  getList()
}

const onClearKeyword = () => {
  keyword.value = ''
  getList()
}

const onSearch = async () => {
  getList()
}

const onReset = async () => {
  nodeId.value = ''
  keyword.value = ''
  getList()
}


const onBindingUser = async (hosId: any, orgId: any, customerName: any, type: number) => {
  const res = await getUserBindingCustomerList({hosId, orgId})
  const arr = []
  for (let mo of res.arr) {
    arr.push(mo.uid)
  }
  editForm.type = type
  editForm.customerName = customerName
  editForm.hosId = hosId
  editForm.orgId = orgId
  editForm.uids = arr
  showEditModel.value = true
}

const pullHos = async (customerId: any) => {
  const res = await pullHospitalList(customerId)
  if (!res) return
  ElMessage.success('拉取成功')
}

const onCloseEdit = () => {
  formRef.resetFields()
  showEditModel.value = false
}

const bindingUser = async (formRef: FormInstance | undefined) => {
  if (!formRef) {
    return
  }
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      const res = await editUserBindingCustomer({
        type: editForm.type,
        hosId: editForm.hosId,
        orgId: editForm.orgId,
        uids: editForm.uids
      })
      if (!res) return false
      formRef.resetFields()
      showEditModel.value = false
      ElMessage({
        type: 'success',
        message: '已提交'
      })
      return true
    } else {
      return false
    }
  })
}

async function getList() {
  loading.value = true
  try {
    const res = await getNodeCustomerList({
      nodeId: nodeId.value,
      customerName: keyword.value,
      pageNo: 1,
      pageSize: 10000
    })
    tableData.value = res.arr
    // if (nodeOptions.value.length <= 0) {
    //   const opts = []
    //   for (let item of res.arr) {
    //     opts.push({
    //       label: item.nodeName,
    //       value: item.nodeId
    //     })
    //   }
    //   nodeOptions.value = opts
    // }

  } finally {
    setTimeout(() => loading.value = false, 200)
  }
}


</script>

<style scoped lang="scss">
@import "@/global.scss";

.tem-table {
  $a: 100%;
  $b: 32px;

  height: calc(#{$a} - #{$b});
  //height: 300px;
  //height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: var(--ap-box-shadow-light);
  box-sizing: border-box;
  padding: 10px;
}


.tem-table-box {
  flex: 1;
  overflow: hidden;
}
</style>